package com.cmonbaby.hotfix.demo.activities;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import com.cmonbaby.hotfix.FixDexUtils;
import com.cmonbaby.hotfix.demo.BaseActivity;
import com.cmonbaby.hotfix.demo.R;
import com.cmonbaby.hotfix.utils.Constants;
import com.cmonbaby.hotfix.utils.FileUtils;

import java.io.File;
import java.io.IOException;

public class SecondActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        fixBug();
    }

    public void show(View view) {
        int a = 10;
        int b = 1;
        Toast.makeText(this, "math >>> " + a / b, Toast.LENGTH_SHORT).show();
    }

    public void fix(View view) {
        fixBug();
    }

    // classes2.dex ---> /storage/emulated/0/classes2.dex
    private void fixBug() {
        // 通过服务端接口下载dex文件，如：v1.3.3版本有某个热修复dex文件（暂定classes2.dex）
        File sourceFile = new File(Environment.getExternalStorageDirectory(), Constants.DEX_NAME);
        // 目标路径：私有目录
        File targetFile = new File(getDir(Constants.DEX_DIR, Context.MODE_PRIVATE).getAbsolutePath()
                + File.separator + Constants.DEX_NAME);
        // 如果存在，清理之前修复过的dex文件
        if (targetFile.exists()) {
            boolean delete = targetFile.delete();
            if (delete) {
                Toast.makeText(this, "删除已存在dex文件", Toast.LENGTH_SHORT).show();
            }
        }

        try {
            // 复制已修复dex文件到私有目录
            FileUtils.copyFile(sourceFile, targetFile);
            Toast.makeText(this, "复制dex文件完成", Toast.LENGTH_SHORT).show();
            // 开始修复dex
            FixDexUtils.loadFixedDex(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
